// pages/cleverWater.js
import http from '../../utils/http.js';
import QRCode from '../../utils/weapp-qrcode.js'
const W = wx.getSystemInfoSync().windowWidth;
const rate = 750.0 / W;
const qrcodeWidth = 290 / rate;

var app = getApp()
var ctx = null
var tid = null
var scrollTimer = null
var drinkNumInterval = null
// 模拟 cancelAnimationFrame
function abortAnimationFrame(id) {
  clearTimeout(id)
}
var tabRects = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    familys:[],
    scrollLeftTab: 0,
    scrollLeft: 0,
    targetNum: 0,
    drinkNumReal: 0,
    drinkNum: 0,
    progress: 0,
    bindShow: false,
    drinkShow: false,
    drinkrules: 500 + 42 * app.globalData.screenScale, //测量尺刻度的数量
    drinkValue: 0, // 刻度尺值
    drink: 0,
    qrcodeShow: false,
    qrcodeWidth: qrcodeWidth,
    historyQuantity: "",  // 历史饮水
    todayQuantity: "", // 今日家庭饮水
    totalQuantity: "", // 今日家庭饮水
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.drawPool()
    this.getData()
    app.globalData.lastPath = "/pages/cleverWater/cleverWater"
    if(app.globalData.needLogin){
      wx.showModal({
        title: '提示',
        content: '您还未登录，请去首页登录！',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    abortAnimationFrame(tid)
    if(ctx) {
      ctx.clearRect(0, 0, 160, 160);
    }
    if (drinkNumInterval != null) {
      clearInterval(drinkNumInterval)
      drinkNumInterval = null
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  tabSelect(e){
    let screenScale = app.globalData.screenScale
    let active = e.currentTarget.dataset.id
    if(active == this.data.active){ // 相同不需要继续
      return
    }
    let scrollLeftTab = tabRects[active].left - tabRects[0].left
    this.setData({
      active: active,
      scrollLeftTab: scrollLeftTab
    })
    // 水池切换
    if (this.data.active != this.data.familys.length){
      this.showPool()
    }
  },
  // 编辑
  naviToAddFamily(){
    wx.navigateTo({
      url: '/pages/addFamily/addFamily?type=1&userId=' + this.data.familys[this.data.active].id, // 0 添加 1 编辑 
    })
  },
  addFamily(){
    if (this.data.hasMachine){ // 已经有机器了
      wx.navigateTo({
        url: '/pages/addFamily/addFamily?type=0', // 0 添加 1 编辑
      })
      return
    }
    this.setData({
      bindShow: true
    })
  },
  naviToBindDrinking(){
    this.setData({
      bindShow: false
    })
    //wx.navigateTo({
    //  url: '/pages/bindDrinking/bindDrinking?hasNextStep=1',
    //})
    wx.navigateTo({
      url: '/pages/drinking/drinking',
    })
  },
  cancel(){
    this.setData({
      bindShow: false
    })
  },
  drawPool(){
    if(!ctx){
      ctx = wx.createCanvasContext('pool')
    }
        
    this.wave(ctx, this.data.drinkNum / this.data.targetNum * 100);
  },
  wave (ctx, oRange){
    ctx.clearRect(0, 0, 160, 160);
    var that = this
    var M = Math;
    var Sin = M.sin;
    var Cos = M.cos;
    var Sqrt = M.sqrt;
    var Pow = M.pow;
    var PI = M.PI;
    var Round = M.round;
      // 线宽
    var lineWidth = 2;
    var oW =  160 - lineWidth * 2;
    var oH =  160 - lineWidth * 2;
  
    // 大半径
    var r = (oW / 2);
    var cR = r - lineWidth;
    ctx.beginPath();
    ctx.lineWidth = lineWidth;
    // 水波动画初始参数
    var axisLength = 2 * r;  // Sin 图形长度
    var unit = axisLength / 9; // 波浪宽
    var range = .4 // 浪幅
    var nowrange = range;
    var xoffset = lineWidth  //8 * lineWidth; // x 轴偏移量
    
    var data = ~~(oRange) / 100;   // 数据量
    
    var sp = 0; // 周期偏移量
    var nowdata = 0;
    var waveupsp = 0.006; // 水波上涨速度
    // 圆动画初始参数
    var arcStack = [];  // 圆栈
    var bR = r;
    var soffset = -(PI / 2); // 圆动画起始位置
    var circleLock = true; // 起始动画锁
    // 获取圆动画轨迹点集
    for (var i = soffset; i < soffset + 2 * PI; i += 1 / (8 * PI)) {
      arcStack.push([
        r + bR * Cos(i),
        r + bR * Sin(i)
      ])
    }
    // 圆起始点
    var cStartPoint = arcStack.shift();
    ctx.strokeStyle = "#1c86d1";
    ctx.moveTo(cStartPoint[0], cStartPoint[1]);
    // 开始渲染
    render();
    function drawSine() {
      ctx.beginPath();
      ctx.save();
      var Stack = []; // 记录起始点和终点坐标
      for (var i = xoffset; i <= xoffset + axisLength; i += 20 / axisLength) {
        var x = sp + (xoffset + i) / unit;
        var y = Sin(x) * nowrange;
        var dx = i;
        var dy = 2 * cR * (1 - nowdata) + (r - cR) - (unit * y);
        ctx.lineTo(dx, dy);
        Stack.push([dx, dy])
      }
      // 获取初始点和结束点
      var startP = Stack[0]
      var endP = Stack[Stack.length - 1]
      ctx.lineTo(xoffset + axisLength, oW);
      ctx.lineTo(xoffset, oW);
      ctx.lineTo(startP[0], startP[1])
      ctx.fillStyle = "#62BBFF";
  
      ctx.fill();
      ctx.restore();
    }
    function drawText() {
      ctx.globalCompositeOperation = 'source-over';
      var size = 48 //0.4 * cR;
      ctx.font = 'bold ' + size + 'px DINAlternate-Bold,DINAlternate';
      var number = (nowdata.toFixed(2) * 100).toFixed(0);
      
    
      var txt = (number/100) * that.data.targetNum  //number+ '%';
      var fonty = r + size / 2;
      var fontx = r - size /2;
    
      ctx.fillStyle = '#1A1A1A'
      ctx.textAlign = 'center';
      ctx.fillText(txt, r, r)
      size = 12
  
      txt = "当天总饮水量(毫升)"
      ctx.font =  size + 'px PingFangSC-Regular,PingFang SC';
      fonty = r + size + 10
      fontx = r + size / 2
      ctx.fillText(txt, fontx, fonty)
    }
  
    //最外层淡蓝色圆圈
    function outCircle() {
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.strokeStyle = '#C8E7FF';
      ctx.arc(r, r, cR, 0, 2 * Math.PI);
      ctx.stroke();
      ctx.restore();
      ctx.beginPath();
    }
    //橘黄色进度圈
    function orangeCircle() {
      ctx.beginPath();
      ctx.strokeStyle = '#62BBFF';
      //使用这个使圆环两端是圆弧形状
      ctx.lineCap = 'round';
      ctx.arc(r, r, cR - 5, 0 * (Math.PI / 180.0) - (Math.PI / 2), (nowdata * 360) * (Math.PI / 180.0) - (Math.PI / 2));
      ctx.stroke();
      ctx.save()
    }
    //裁剪中间水圈
    function clipCircle() {
      ctx.beginPath();
      ctx.arc(r, r, cR, 0, 2 * Math.PI, false);
      ctx.clip();
    }
    //渲染canvas
    function render() {
      abortAnimationFrame(tid);
  
      ctx.clearRect(0, 0, oW, oH);
      
      //淡蓝色外圈  
      outCircle();
      //最外层进度圈
      //orangeCircle();
      //裁剪中间水圈  
      clipCircle();
      // 控制波幅
      
      if (data >= 0.85) {
        if (nowrange > range / 4) {
          var t = range * 0.01;
          nowrange -= t;
        }
      } else if (data <= 0.1) {
        if (nowrange < range * 1.5) {
          var t = range * 0.01;
          nowrange += t;
        }
      } else {
        if (nowrange <= range) {
          var t = range * 0.01;
          nowrange += t;
        }
        if (nowrange >= range) {
          var t = range * 0.01;
          nowrange -= t;
        }
      }
      if ((data - nowdata) > 0) {
        nowdata += waveupsp;
      }
      if ((data - nowdata) < 0) {
        nowdata -= waveupsp
      }
      sp += 0.07;
      // 开始水波动画
      drawSine();
   
      
      // 写字
      drawText();
  
      ctx.draw();
      
      tid = doAnimationFrame(render);
    }
  
    var lastFrameTime = 0;
    // 模拟 requestAnimationFrame
    function doAnimationFrame(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastFrameTime));
      
      var id = setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
      lastFrameTime = currTime + timeToCall;
      return id;
    };
  },
  openDinkShow(){
    this.setData({
      drinkShow: true
    })
  },
  onClose(){
    this.setData({
      drinkShow: false,
      qrcodeShow: false
    })
  },
  scrollChange(e) {
    let scale = 1 //app.globalData.screenScale
    let scrollLeft = e.detail.scrollLeft
    let unit = (18/2)*scale
    // console.log('scale',scale)
    console.log(new Date().getTime())
    let unit10 = (unit*10+1) // 每10个小格子的长度
    let drinkValue1 = parseInt(scrollLeft / unit10)*100 // 整数位
    let drinkValue2 = parseInt(scrollLeft % unit10 -1)/unit *10 // 小数位
    drinkValue2 = drinkValue2 >= 0 ? drinkValue2 : 0
    // console.log("drinkValue1",drinkValue1)
    // console.log("drinkValue2",drinkValue2)
    let drinkValue =  Math.round((drinkValue1 + drinkValue2)/10)*10
    this.setData({
      drinkValue
    })
    // 200 毫秒后修正
    if(scrollTimer){
      clearTimeout(scrollTimer)
    }
    // 修正真实的刻度
    let ruleValue = drinkValue / 10
    scrollLeft = parseInt(ruleValue/10) * unit10 +  ruleValue % 10 * unit + 1
    
    scrollTimer = setTimeout(() => {
      this.setData({
        scrollLeft
      })
    }, 200);

  },
  drinkChange(){
    this.setData({
      drink: this.data.drinkValue,
      drinkShow: false,
    })
    let params = {
      quantity: this.data.drinkValue,
      userId: this.data.familys[this.data.active].id
    }
    http.request("/drinkRecords/add",params)
    .then(res=>{
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
      this.getData()
    })
    .catch(res=>{

    })
  },
  createQrcode(text) {
    this.data.qrcode = new QRCode('canvas', {
      // usingIn: this,
      text: text,
      // image: '/images/bg.jpg',
      // padding: 12,
      width: qrcodeWidth,
      height: qrcodeWidth,
      // colorDark: "#1CA4FC",
      // colorLight: "white",
      correctLevel: QRCode.CorrectLevel.H,
      callback: (res) => {
        // 生成二维码的临时文件
        console.log(res.path)
      }
    });
  },
  openQrcodeShow(){
    this.setData({
      qrcodeShow: true
    })
    let id = this.data.familys[this.data.active].id
    this.createQrcode(id + '')
  },
  scanCode() {
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let params = {
          friendId: res.result
        }
        http.request("/drinkUsers/scanFriend", params)
          .then(res => {
            wx.showToast({
              title: res.massage,
              icon: 'none'
            })
          })
          .catch(res => {

          })
      }
    })
  },
  naviToHistory(){
    wx.navigateTo({
      url: '/pages/history/history?userId=' + this.data.familys[this.data.active].id,
    })
  },
  naviToFamilyDrink(){
    wx.navigateTo({
      url: '/pages/familyDrink/familyDrink',
    })
  },
  naviToDrinkRank(){
    wx.navigateTo({
      url: '/pages/dinkRank/drinkRank',
    })
  },
  naviToDrinkIndex(){
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  naviToDrinkJH(){
    wx.navigateTo({
      url: '/pages/drinking/drinking',
    })
  },
  naviToDrinkTS(){
    wx.navigateTo({
      url: '/pages/suggest/suggest',
    })
  },
  getData(){
    http.request("/drinkRecords/index")
    .then(res=>{
      console.log(res)
      if(res.data.list.length != 0) {
        app.globalData.isfirstMember = false
      }else{
        app.globalData.isfirstMember = true
      }
      this.setData({
        familys: res.data.list,
        hasMachine: res.data.hasMachine
      })
      http.request("/drinkRecords/familyList")
      .then(res=>{
        this.setData({
          historyQuantity: res.data.historyQuantity,
          todayQuantity: res.data.todayQuantity,
          totalQuantity: res.data.totalQuantity
        })
        this.setTabs()
        this.showPool()
      })
      .catch(res=>{

      })
    })
    .catch(res=>{

    })
  },
  showDetail:function (e) {
    let code = e.currentTarget.dataset.dvcode;
    wx.navigateTo({
      url: '/pages/dinkDetail/drinkDetail?code='+code
    })
  },
  setTabs(){
    var query = wx.createSelectorQuery();
    query.selectAll('.tab').boundingClientRect((rect) => {
      tabRects = rect
    }).exec()
  },
  showPool(){
    if (drinkNumInterval != null){
      clearInterval(drinkNumInterval)
      drinkNumInterval = null
    }
    //let drinkNumReal = this.data.familys[this.data.active].todayWaterQuantity // 饮水量
    //let targetNum = this.data.familys[this.data.active].waterQuantityPlan // 目标饮水量
    let drinkNumReal = this.data.totalQuantity // 饮水量
    let targetNum = 5000 // 目标饮水量
    let drinkNum = 0 // 饮水量变化
    let animationTime = 1500
    let animationTimeReal = animationTime
  
    drinkNumInterval = setInterval(() => {
      let progress = 0
      if (animationTime <= 0) {
        drinkNum = drinkNumReal
        if (drinkNumInterval) {
          clearInterval(drinkNumInterval)
          drinkNumInterval = null
        }
        progress = parseInt(this.data.drinkNum / targetNum * 100)
        this.setData({
          drinkNum,
          progress: progress > 100 ? 100 : progress
        })
        return
      }
      drinkNum += parseInt(drinkNumReal * 100 / animationTimeReal)
      progress = parseInt(this.data.drinkNum / targetNum * 100)
      this.setData({
        drinkNum,
        progress: progress > 100 ? 100 : progress
      })
      animationTime -= 100

    }, 100)
  }
})